package com.oj.interceptor;

import com.oj.config.OJConfig;
import com.oj.entity.User;
import com.oj.service.UserService;
import com.oj.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class ApiInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    //Controller逻辑执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            String ipAddress = IpUtil.getIpAddr(request);
            if (OJConfig.IsBlockIpList(ipAddress)) {
                //log.error(ipAddress + " is in black ip list. ==> " + request.getRequestURI());
                return false;
            }

            log.info(ipAddress + " - "+ request.getHeader("User-Agent") + ": ? ==> API: " + request.getRequestURI());
        } catch (Exception e) {
            // TODO: handle exception
            log.error("ApiInterceptor: Exception");
            return true;
        }

        return true;
    }

    //Controller逻辑执行完毕但是视图解析器还未进行解析之前
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    //Controller逻辑和视图解析器执行完毕
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
